package com.hmall.search.conf;

import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.json.jackson.JacksonJsonpMapper;
import co.elastic.clients.transport.ElasticsearchTransport;
import co.elastic.clients.transport.rest_client.RestClientTransport;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.hmall.search.properties.EsProperties;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpHost;
import org.elasticsearch.client.RestClient;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PreDestroy;
import java.io.IOException;

/**
 * @author Mr.M
 * @version 1.0
 * @description Elasticsearch配置类
 * @date 2024/8/19 18:09
 */
@Slf4j
@Configuration
@EnableConfigurationProperties(EsProperties.class)
public class EsConfiguration {
    private ElasticsearchTransport transport;

    @Bean
    public ElasticsearchClient esClient(EsProperties esProperties) {
        // 创建 ObjectMapper 实例
        ObjectMapper objectMapper = new ObjectMapper();
        // 添加 JavaTimeModule 以支持 LocalDateTime 类型
        objectMapper.registerModule(new JavaTimeModule());
        // 配置忽略未知字段
        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); // 添加这行

        // 创建 RestClient
        RestClient restClient = RestClient.builder(
                new HttpHost(esProperties.getHost(), esProperties.getPort())).build();

        // Create the transport with a Jackson mapper
        transport = new RestClientTransport(
                restClient, new JacksonJsonpMapper(objectMapper));

        // And create the API client
        ElasticsearchClient esClient = new ElasticsearchClient(transport);
        return esClient;
    }

    // 应用关闭时自动调用此方法
    @PreDestroy
    public void closeTransport() {
        if (transport != null) {
            try {
                // 关闭底层的RestClient
                transport.close();

                log.info("关闭ES的transport完毕");
            } catch (IOException e) {
                // 记录错误日志，避免影响应用关闭
                log.error("关闭ES的transport出错", e);
            }
        }
    }

}